package com.garbagecan.cachestudy.ehcache;

import java.net.URL;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.garbagecan.cachestudy.User;

public class DiskCacheExample {

	private static Log log = LogFactory.getLog(DiskCacheExample.class);

	private CacheManager cacheManager;

	private int cacheCount = 5;

	private int dataCount = 100;

	public static void main(String[]args) {
		log.info("java.io.tmpdir:" + System.getProperty("java.io.tmpdir"));

		DiskCacheExample t = new DiskCacheExample();
		t.start();
		t.writeToCache();
		t.readFromCache();
		t.stop();
	}

	private void start() {
		URL url = CacheManagerExample.class.getResource("ehcache.xml");
		cacheManager = new CacheManager(url);
		log.info(cacheManager.getDiskStorePathManager());
	}

	private void stop() {
		cacheManager.shutdown();
	}
	
	private void writeToCache() {
		// Write cache data to java.io.tmpdir
		for(int idxCache = 0; idxCache < cacheCount; idxCache++) {
			Cache cache = new Cache("myCache" + idxCache, 100, MemoryStoreEvictionPolicy.FIFO, true, null, true, 100, 100, true, 120, null);
			cacheManager.addCache(cache);
			for(int i = 0 ; i < dataCount ; i++) {
				User user = new User();
				user.setName("name" + i);
				cache.put(new Element("name" + i, user));
			}
			cache.flush();
		}
	}
	
	private void readFromCache() {
		log.info("cache name size:" + cacheManager.getCacheNames().length);
		for (String name : cacheManager.getCacheNames()) {
			log.info("cache name: " + name);
		}
		for(int idxCache = 0; idxCache < cacheCount; idxCache++) {
			Cache cache = cacheManager.getCache("myCache" + idxCache);
			for(int i = 0 ; i < dataCount ; i++) {
				User user = (User)cache.get("name" + i).getValue();
			}
		}
	}
}
